<template>
  <div class="order-page">
    <!-- 地址卡片 -->
    <div class="address-section">
      <el-card class="address-card" v-if="currentAddress">
        <div class="address-info">
          <p>
            <strong>{{ currentAddress.receiver }}</strong>
            {{ currentAddress.phone }}
          </p>
          <p>{{ currentAddress.region.fullName }} {{ currentAddress.regionDetail }}</p>
        </div>
        <div>
          <el-button type="text" @click="addressDialogVisible = true">选择/新增地址</el-button>
        </div>
      </el-card>

      <div v-else class="address-empty">
        <el-empty description="您还没有收货地址！">
          <el-button type="primary" @click="openAddAddress">新增地址</el-button>
        </el-empty>
      </div>
    </div>

    <!-- 我的订单头部 -->
    <header class="order-header">
      <div class="order-header-content">
        <p>
          <i class="el-icon-s-order" style="color:#ff6700;font-weight:600"></i>
          我的订单
        </p>
      </div>
    </header>

    <!-- 订单列表 -->
    <section v-if="orders.length" class="order-content">
      <article v-for="group in orders" :key="group.orderNo" class="order-card">
        <!-- 订单信息 -->
        <div class="order-meta">
          <span>订单编号：{{ group.orderNo }}</span>
          <span>下单时间：{{ formatDate(group.createdTime) }}</span>
          <el-tag :type="statusType(group.status)" size="small">
            {{ statusTxt(group.status) }}
          </el-tag>
        </div>

        <!-- 商品列表 -->
        <ul class="goods-list">
          <li v-for="item in group.items" :key="item.id" class="goods-row">
            <router-link class="img-box" :to="`/goods/details?productID=${item.goodId}`">
              <img :src="imgUrl(item.goodPic)" alt />
            </router-link>
            <div class="goods-info">
              <router-link :to="`/goods/details?productID=${item.goodId}`" class="name">
                {{ item.goodName }}
              </router-link>
              <p class="desc">{{ item.goodDesc || '暂无描述' }}</p>
            </div>
            <div class="unit-price">¥{{ item.dealPrice }}</div>
            <div class="num">x{{ item.count }}</div>
            <div class="row-total">¥{{ (item.dealPrice * item.count).toFixed(2) }}</div>
          </li>
        </ul>

        <!-- 底部操作栏 -->
        <footer class="order-bar">
          <div class="pay-summary">
            共 {{ group.totalNum }} 件
            <em>合计：¥{{ group.totalPay }}</em>
          </div>
          <div class="order-actions" v-if="group.status === 0">
            <el-button type="danger" size="small" @click="cancelOrder(group)">取消订单</el-button>
            <el-button type="primary" size="small" @click="payOrder(group)">去支付</el-button>
          </div>
        </footer>

      </article>
    </section>

    <!-- 空订单 -->
    <div v-else class="order-empty">
      <el-empty description="您的订单还是空的！">
        <el-button type="primary" @click="$router.push('/')">去逛逛</el-button>
      </el-empty>
    </div>

    <!-- 地址选择弹窗 -->
    <el-dialog title="管理收货地址" :visible.sync="addressDialogVisible" width="600px">
      <el-radio-group v-model="selectedAddressId" class="address-list">
        <el-radio v-for="addr in addressList" :key="addr.id" :label="addr.id">
          {{ addr.receiver }} {{ addr.phone }} {{ addr.region.fullName }} {{ addr.regionDetail }}
          <el-button type="text" size="mini" @click.stop="editAddress(addr)">修改</el-button>
        </el-radio>
      </el-radio-group>

      <div style="margin-top: 10px;">
        <el-button type="primary" @click="openAddAddress">新增地址</el-button>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddress">确认选择</el-button>
      </div>
    </el-dialog>

    <!-- 地址编辑/新增弹窗 -->
    <el-dialog title="编辑地址" :visible.sync="editAddressDialogVisible" width="500px">
      <el-form :model="editAddressForm" label-width="80px">
        <el-form-item label="收货人">
          <el-input v-model="editAddressForm.receiver"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="editAddressForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="地区">
          <el-cascader
              v-model="editAddressForm.regionId"
              :options="regionOptions"
              :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name', children: 'children' }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="editAddressForm.regionDetail"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editAddressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      orders: [],
      addressDialogVisible: false,
      editAddressDialogVisible: false,
      addressList: [],
      selectedAddressId: null,
      currentAddress: null,
      editAddressForm: {},
      regionOptions: []
    };
  },
  mounted() {
    this.loadOrders();
    this.loadAddressList();
    this.loadRegionTree();
  },
  methods: {
    async loadOrders() {
      try {
        const userId = parseInt(localStorage.getItem("userId")) || 1;
        const res = await this.$axios.get("/api/v1/order/getByMemberId", {
          params: { memberId: userId }
        });
        if (res.data.code === 200 && res.data.data) {
          const arr = Array.isArray(res.data.data)
              ? res.data.data
              : Object.values(res.data.data);
          this.orders = arr
              .map(o => ({
                ...o,
                items: (o.orderItems || []).map(g => ({
                  ...g,
                  dealPrice:
                      (typeof g.dealPrice === "object"
                          ? g.dealPrice.parsedValue
                          : g.dealPrice) || 0,
                  goodPic: g.goodPic.startsWith("http")
                      ? g.goodPic
                      : this.$target + g.goodPic
                })),
                totalNum: (o.orderItems || []).reduce((s, g) => s + g.count, 0),
                totalPay:
                    (typeof o.totalPay === "object"
                        ? o.totalPay.parsedValue
                        : o.totalPay) || 0
              }))
              .sort((a, b) => {
                if (a.status === 0 && b.status !== 0) return -1;
                if (b.status === 0 && a.status !== 0) return 1;
                return new Date(b.createdTime) - new Date(a.createdTime);
              });
        } else {
          this.$message.error(res.data.msg || "加载订单失败");
        }
      } catch {
        this.$message.error("加载订单失败");
      }
    },

    async loadAddressList() {
      try {
        const userId = parseInt(localStorage.getItem("userId")) || 1;
        const res = await this.$axios.get(`/api/v1/address/get/${userId}`);
        if (res.data.code === 200) {
          this.addressList = res.data.data || [];
          const defaultAddr = this.addressList.find(a => a.default) || this.addressList[0];
          this.currentAddress = defaultAddr || null;
          this.selectedAddressId = defaultAddr ? defaultAddr.id : null;
        }
      } catch {
        this.$message.error("加载地址失败");
      }
    },

    async loadRegionTree() {
      try {
        const res = await this.$axios.get("/api/v1/address/regions/tree");
        if (res.data.code === 200) this.regionOptions = res.data.data;
      } catch {
        this.$message.error("加载地址失败");
      }
    },

    openAddAddress() {
      this.editAddressForm = { receiver: "", phone: "", regionId: null, regionDetail: "" };
      this.editAddressDialogVisible = true;
    },

    editAddress(addr) {
      this.editAddressForm = JSON.parse(JSON.stringify(addr));
      this.editAddressDialogVisible = true;
    },

    async saveAddress() {
      try {
        const res = await this.$axios.post("/api/v1/address/update", this.editAddressForm);
        if (res.data.code === 200) {
          this.$message.success("保存成功");
          await this.loadAddressList();
          this.editAddressDialogVisible = false;
        } else {
          this.$message.error(res.data.msg || "保存失败");
        }
      } catch {
        this.$message.error("保存失败");
      }
    },

    confirmAddress() {
      this.currentAddress = this.addressList.find(a => a.id === this.selectedAddressId);
      this.addressDialogVisible = false;
    },

    // ========= 订单操作 =========
    async payOrder(order) {
      try {
        console.log(order)
        const res = await this.$axios.post("/api/v1/order/pay", {
          orderNo:order.orderNo,
          memberId:localStorage.getItem("userId")
        })
        if (res.data.code === 200) {
          this.$message.success("支付成功");
          this.loadOrders();
        } else {
          this.$message.error(res.data.msg || "支付失败");
        }
      } catch {
        this.$message.error("支付失败");
      }
    },

    async cancelOrder(order) {
      try {
        const res = await this.$axios.delete("/api/v1/order/cancel", { params: { orderNo: order.orderNo } });
        if (res.data.code === 200) {
          this.$message.success("订单已取消");
          this.loadOrders();
        } else {
          this.$message.error(res.data.msg || "取消失败");
        }
      } catch {
        this.$message.error("取消失败");
      }
    },

    // ========= 辅助方法 =========
    formatDate(val) {
      if (!val) return "";
      const d = new Date(val);
      return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}`;
    },
    statusTxt(st) {
      const map = ["待付款", "待发货", "已发货", "已完成", "已关闭"];
      return map[st] || "未知";
    },
    statusType(st) {
      return ["warning", "info", "success", "success", "danger"][st] || "info";
    },
    imgUrl(src) {
      return src && src.startsWith("http") ? src : (this.$target || "") + src;
    }
  }
};
</script>


<style scoped>
.order {
  background: #f5f5f5;
  padding-bottom: 20px;
}

.order-header {
  height: 64px;
  border-bottom: 2px solid #ff6700;
  background: #fff;
  margin-bottom: 20px;
}

.order-header-content {
  width: 1225px;
  margin: 0 auto;
}

.order-header p {
  font-size: 24px;
  line-height: 64px;
  font-weight: bold;
  color: #424242;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 10px 0;
}

.order-card {
  margin: 0 auto 30px;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, .05);
}

.order-meta {
  display: flex;
  justify-content: space-between;
  padding: 12px 20px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}

.goods-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.goods-row {
  display: grid;
  grid-template-columns:80px 1fr 100px 80px 100px;
  gap: 15px;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f5f5f5;
}

.goods-row:last-child {
  border-bottom: none;
}

.img-box img {
  width: 80px;
  height: 80px;
  object-fit: contain;
}

.goods-info .name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.goods-info .desc {
  font-size: 12px;
  color: #888;
  margin-top: 6px;
}

.unit-price, .num, .row-total {
  text-align: center;
}

.row-total {
  color: #ff6700;
  font-weight: bold;
}

.order-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
}

.order-bar .pay-summary {
  font-size: 14px;
}

.order-bar .pay-summary em {
  font-size: 20px;
  color: #ff6700;
  margin-left: 6px;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.order-actions .el-button {
  border-radius: 4px;
  font-weight: 500;
}

.order-actions .el-button--primary {
  background-color: #ff6700;
  border-color: #ff6700;
}

.order-actions .el-button--primary:hover {
  background-color: #ff8a33;
  border-color: #ff8a33;
}


.order-bar .receiver {
  font-size: 14px;
  color: #666;
}

.order-bar .pay-summary {
  font-size: 14px;
}

.order-bar .pay-summary em {
  font-size: 20px;
  color: #ff6700;
  margin-left: 6px;
}

@media (max-width: 768px) {
  .order-header-content, .order-card {
    width: 100%;
    padding: 0 10px;
  }

  .goods-row {
    grid-template-columns:80px 1fr;
    grid-template-rows:auto auto;
  }

  .unit-price, .num, .row-total {
    justify-self: end;
  }
}
</style>
